package system.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import system.LoginContext;
import system.base.User;
import system.base.UserMenuinfo;
import system.base.Warehouse;

import com.apep.crypt.CryptUtils;
import com.apep.permission.CookieUtils;
import com.apep.permission.PermissionFilter;
import com.hitrust.gs.lib.GSAutoAuditongDateConfigurator;
import com.hitrust.gs.lib.GSSystemConfigurator;

import framework.core.Config;
import framework.core.ConstDefine;
import framework.core.DBConnection;
import framework.core.Logger;
import framework.core.ObjectList;
import framework.core.SrvContext;

public class ProjectManagerServlet extends HttpServlet{
	
	private void redirectToPath(HttpServletRequest request, HttpServletResponse response, String path) throws Exception {
		getServletConfig().getServletContext().getRequestDispatcher(path)
		.forward(request, response);
	}
	
	private void redirectToError(HttpServletRequest request, HttpServletResponse response) throws Exception {
		GSAutoAuditongDateConfigurator gs = GSAutoAuditongDateConfigurator.getInstance();
		String errorUrl = gs.getBackProjectManagerErrorUrl();
		if(errorUrl==null||errorUrl.equals("")){
			redirectToPath(request, response, "/system/login.jsp");

		}else{
			response.sendRedirect(errorUrl);
		}
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {		
		String query = req.getQueryString();
		try {
			SrvContext context = new SrvContext(req, resp);
			String tDecryptedStr = CryptUtils.decrypt(query);
			String[] tSpliteQueryStrArray = StringUtils.split(tDecryptedStr, "=");
			if(tSpliteQueryStrArray.length!=2){
				redirectToError(req, resp);
				return;
			}
			User user = User.fetchByName(tSpliteQueryStrArray[1]);
			if(user==null){
				redirectToError(req, resp);
				return;
			}else{
				Warehouse warehouse = Warehouse.fetchByCode(DBConnection.open(),user.getWarehouseCode());		
				//是否有权限进行视图切换
				boolean bl=false;
				if(user.getCode().equals(ConstDefine.T_USER_SUPERADMIN_CODE)){
				    if ("true".equalsIgnoreCase(GSSystemConfigurator.getParam("gs.view.switch"))) {
				        bl=true;
		            }
				}else{
		    		ObjectList list=UserMenuinfo.fetchbyUserId(user.getId(), DBConnection.open());
		            for (int i = 0; i < list.size(); i++) {
		                UserMenuinfo um=(UserMenuinfo) list.get(i);
		                if(um.getMenuCode()==ConstDefine.VIEW_SWITCH){
		                    bl=true;
		                    break;
		                }
		            }
				}
		        LoginContext loginContext = new LoginContext();
		        loginContext.setView(bl);
				loginContext.setUser(user);
				loginContext.setWarehouse(warehouse);
		        loginContext.setDev(Config.isDebug());
		        loginContext.setProject(true);
		        context.setSessionValue("LoginContext", loginContext);
				context.m_res.setHeader("location", context.m_req.getSession().getId());
				redirectToPath(req, resp, "/system/index.jsp");

				CookieUtils.setValue(context.m_req, context.m_res, PermissionFilter.COOKIE_USER_CODE_NAME, user.getCode(), PermissionFilter.EIGHT_HOURS);
				CookieUtils.setValue(context.m_req, context.m_res, PermissionFilter.COOKIE_PASSWORD_NAME, user.getPassword(), PermissionFilter.EIGHT_HOURS);

			}
		} catch (Exception e) {
			Logger.logException("ProjectManagerServlet.处理异常出错", e);
		}
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}
}
